using Devil;
using UnityEngine;

namespace GameToolkit.BehaviourTree
{
    [System.Serializable]
    [CompositeTitle("随机选择", Description = "Random Selector")]
    [CompositeCategory]
    [CompositeIcon("0e8ec6657914e714196e16340921a10f")]
    public class RandomSelector : ExecutableComposite
    {
        [SerializeField, Tooltip("随机循环次数（-1 表示无限次）")]
        int m_Loops;

        public override BehaviourTreeObject Create()
        {
            return new Impl();
        }

        class Impl : ControllerNode, ILoopController
        {
            int mRandomIndex;
            ExecutableEntry mSelected;
            int mLoops;
            RandomSelector mCfg;

            protected override void OnCreate(BehaviourTreePlayer player)
            {
                mCfg = composite as RandomSelector;
            }

            protected override void OnDestroy(BehaviourTreePlayer player)
            {
            }

            protected override NodeState GetNextBehaviour(BehaviourTreePlayer player, out ExecutableEntry nextNode)
            {
                if (mRandomIndex >= 0 && mRandomIndex < ChildCount)
                {
                    nextNode = GetChild(mRandomIndex);
                    mRandomIndex = -1;
                    mSelected = nextNode;
                    return NodeState.Running;
                }
                else
                {
                    nextNode = null;
                    if (mCfg.m_Loops < 0 || mCfg.m_Loops > mLoops)
                        return NodeState.Running;
                    else
                        return mSelected == null ? NodeState.Failed : mSelected.State;
                }
            }

            protected override void OnStart(BehaviourTreePlayer player)
            {
                mSelected = null;
                mLoops = 1;
                mRandomIndex = ParallelDispatcher.GetRandomValue(0, ChildCount);
            }

            protected override void OnStop(BehaviourTreePlayer player)
            {
            }

            void ILoopController.OnResetLoop(BehaviourTreePlayer player)
            {
                mSelected = null;
                mLoops++;
                mRandomIndex = ParallelDispatcher.GetRandomValue(0, ChildCount);
            }
        }
    }
}
